package com.oracle.zebrafreelytraveling.ui;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClientOption;
import com.facebook.drawee.view.SimpleDraweeView;

import com.oracle.zebrafreelytraveling.R;
import com.oracle.zebrafreelytraveling.data.bean.User;
import com.oracle.zebrafreelytraveling.map.MapInfoAdapter;
import com.oracle.zebrafreelytraveling.map.MapUtil;
import com.oracle.zebrafreelytraveling.ui.adapter.ViewPagerAdapter;
import com.oracle.zebrafreelytraveling.ui.fragment.ChatRingFragment;
import com.oracle.zebrafreelytraveling.ui.fragment.ClassifyInfoFragment;
import com.oracle.zebrafreelytraveling.ui.fragment.ForumFragment;
import com.oracle.zebrafreelytraveling.ui.fragment.GetImgDialogFragment;
import com.oracle.zebrafreelytraveling.utils.constant.Constant;
import com.oracle.zebrafreelytraveling.utils.StringUtil;
import com.oracle.zebrafreelytraveling.utils.UserUtil;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.Disposable;

/**
 * Created by yydcnjjw on 2017/7/20.
 */

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, ViewPager.OnPageChangeListener, View.OnClickListener, GetImgDialogFragment.OnCurrentPathListener {

    //底部导航分类
    private static final int NAVIGATION_CLASSIFYINFO = 0;
    private static final int NAVIGATION_FORUM = 1;
    private static final int NAVIGATION_CHATRING = 2;

    //权限请求
    private static final int REQUEST_CODE_PICK_CITY = 10;
    private static final int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 101;


    //保存fragment
    private List<Fragment> mFragmentList;

    private ViewPager mVpMain;//主界面ViewPager
    private ViewPagerAdapter mVpAdapter;
    private DrawerLayout mDrawer;

    private NavigationView mNavigationView;//侧滑菜单
    private SimpleDraweeView naviUserHp;
    private TextView naviUserName;
    private TextView naviLoginOrUp;
    private TextView naviUserSign;
    private SimpleDraweeView naviWeather;

    private BottomNavigationView mBottomNavigationView;
    private Toolbar toolbar;
    private MenuItem menuLocation;

    private FloatingActionButton mFloatingBtn;// 浮动按钮

    //当前的城市
    private String currentCity;
    private AMapLocation mAMapLocation;

    //弹出框
    private EditText mEtDialog;
    private TagFlowLayout mTagFlowLayout;

    private Disposable mDisposable;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initFragment();
        initView();
        initToolbar();
        checkPermission();
    }

    @Override
    protected void onResume() {
        super.onResume();
        try {
            initPersonalInfo();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initView() {
        mBottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_navigation);
        mDrawer = (DrawerLayout) findViewById(R.id.root_layout);
        mNavigationView = (NavigationView) findViewById(R.id.nav_view);
        mVpMain = (ViewPager) findViewById(R.id.viewPager_main);
        mFloatingBtn = (FloatingActionButton) findViewById(R.id.main_float_btn);

        mNavigationView.setNavigationItemSelectedListener(this);
        View naviView = mNavigationView.getHeaderView(0);
        naviUserHp = (SimpleDraweeView) naviView.findViewById(R.id.navi_user_hp);
        naviUserName = (TextView) naviView.findViewById(R.id.navi_user_name);
        naviUserSign = (TextView) naviView.findViewById(R.id.user_location_sign);
        naviLoginOrUp = (TextView) naviView.findViewById(R.id.login_or_up);
        naviWeather = (SimpleDraweeView) naviView.findViewById(R.id.navi_weather);

        mVpAdapter = new ViewPagerAdapter(getSupportFragmentManager(), this, mFragmentList);
        mVpMain.setAdapter(mVpAdapter);
        mVpMain.addOnPageChangeListener(this);

        naviLoginOrUp.setOnClickListener(this);
        naviWeather.setOnClickListener(this);
        mFloatingBtn.setOnClickListener(this);

        naviUserHp.setOnLongClickListener(v -> {
            if (UserUtil.isLogin()){
                GetImgDialogFragment.newInstance().showDialogFragment(getFragmentManager());
            }
            return true;
        });

        mBottomNavigationView.setOnNavigationItemSelectedListener(v -> {
            switch (v.getItemId()) {
                case R.id.navigation_classify:
                    mVpMain.setCurrentItem(NAVIGATION_CLASSIFYINFO);
                    break;
                case R.id.navigation_forum:
                    mVpMain.setCurrentItem(NAVIGATION_FORUM);
                    break;
                case R.id.navigation_chat_ring:
                    mVpMain.setCurrentItem(NAVIGATION_CHATRING);
                    break;
            }
            return true;
        });
    }

    private void initPersonalInfo() {
        if (!UserUtil.isLogin()) {
            naviLoginOrUp.setVisibility(View.VISIBLE);
            naviUserSign.setVisibility(View.GONE);
            naviUserName.setVisibility(View.GONE);
            //TODO 设置占位图 当用户没有登录时
//            naviUserHp.setImageURI();
        } else {
            User user = UserUtil.getUserInfoLocalBySP();
            User userNet = UserUtil.getUserInfoFromSP();
            naviUserSign.setVisibility(View.VISIBLE);
            naviUserName.setVisibility(View.VISIBLE);
            naviLoginOrUp.setVisibility(View.GONE);
            naviUserName.setText(user.getName());
            naviUserName.setText(user.getSign());
            if (user.getHeadImg().length() == 0) {
                naviUserHp.setImageURI(Constant.DOWNLOAD_URL + userNet.getHeadImg());
            } else {
                naviUserHp.setImageURI(user.getHeadImg());
            }
        }
    }

    private void checkPermission(){
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
            if(ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)){
                //解释应用需要的权限
            }else {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
            }
        } else {
            initLocationInfo();
        }
    }

    // 获取定位的基本信息
    private void initLocationInfo() {
        //TODO 天气 位置 等
        MapUtil mapUtil = new MapUtil(new MapInfoAdapter() {
            @Override
            public void locationInfo(AMapLocation location) {
                if (location == null){
                    return;
                }
                String city = location.getCity();
                String district = location.getDistrict();
                currentCity = StringUtil.extractLocation(city, district);
                menuLocation.setTitle(currentCity);
                ForumFragment forumFragment = (ForumFragment) mVpAdapter.getItem(1);
                forumFragment.setCurrentCity(currentCity);
                ChatRingFragment chatRingFragment = (ChatRingFragment) mVpAdapter.getItem(2);
                chatRingFragment.setCurrentCity(currentCity);
                ClassifyInfoFragment classifyInfoFragment = (ClassifyInfoFragment) mVpAdapter.getItem(0);
                classifyInfoFragment.setCurrentCity(currentCity);
                mAMapLocation = location;
            }
        });
        mapUtil.startLocation(MapUtil.LOCATION_ONLY_ONE,
                AMapLocationClientOption.AMapLocationMode.Hight_Accuracy, 10);
        mapUtil.startLocation(MapUtil.LOCATION_KEEP, AMapLocationClientOption.AMapLocationMode.Battery_Saving, 50000);
    }

    private void initToolbar() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayShowTitleEnabled(false);
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeAsUpIndicator(R.drawable.ic_menu_white_24dp);
        }
    }

    private void initFragment() {
        mFragmentList = new ArrayList<>();
        mFragmentList.add(new ClassifyInfoFragment());
        mFragmentList.add(new ForumFragment());
        mFragmentList.add(new ChatRingFragment());
    }

    //    新建帖子对话框
    private void showDialogAddCard() {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle(getString(R.string.addCard));
        View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.dialog_add_card, null);
        mEtDialog = (EditText) view.findViewById(R.id.dialog_add_card_title);
        mTagFlowLayout = (TagFlowLayout) view.findViewById(R.id.dialog_tag);
        mTagFlowLayout.setAdapter(new TagAdapter<String>(getResources().getStringArray(R.array.label)) {
            @Override
            public View getView(FlowLayout parent, int position, String s) {
                TextView tv = (TextView) LayoutInflater.from(MainActivity.this)
                        .inflate(R.layout.tag_dailog_card_et,
                                mTagFlowLayout, false);
                tv.setText(s);
                return tv;
            }
        });
        builder.setView(view);
        builder.setNegativeButton(getString(R.string.cancel), (dialog, which) -> dialog.cancel());
        builder.setPositiveButton(getString(R.string.yes), (dialog, which) -> {
            //TODO 跳转到编辑页面传参 title 并且保存信息到数据库
            String title = mEtDialog.getText().toString();
            String label = StringUtil.formatLabelList(mTagFlowLayout.getSelectedList());
            EtCardActivity.startEditCardActivity(MainActivity.this, title, label);
        });
        builder.show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        menuLocation = menu.findItem(R.id.location);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                mDrawer.openDrawer(GravityCompat.START);
                break;
            case R.id.location:
                startActivityForResult(new Intent(MainActivity.this, CityPickerActivity.class),
                        REQUEST_CODE_PICK_CITY);
                break;
        }
        return true;
    }

    /**********************pageChangeListener***********************/
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        switch (position) {
            case NAVIGATION_CLASSIFYINFO:
                mBottomNavigationView.setSelectedItemId(R.id.navigation_classify);
                break;
            case NAVIGATION_FORUM:
                mBottomNavigationView.setSelectedItemId(R.id.navigation_forum);
                break;
            case NAVIGATION_CHATRING:
                mBottomNavigationView.setSelectedItemId(R.id.navigation_chat_ring);
                break;
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.personal_main:
                if (UserUtil.isLogin()) {
                    PersonalCenterActivity.startPersonalCenterActivity(MainActivity.this,
                            null, PersonalCenterActivity.PERSONAL);
                }
                break;
            case R.id.personal_cards:
                MyCardsActivity.startMyCardsActivity(MainActivity.this);
                break;
            case R.id.personal_love:
                MyConcernActivity.startMyConcernActivity(this);
                break;
            case R.id.personal_friend:
                MyFriendActivity.startMyFriendActivity(this);
                break;
            case R.id.personal_circle:
                MyCircleActivity.startMyCircleActivity(this);
                break;
            case R.id.exit_account:
                UserUtil.exitAccount();
                initPersonalInfo();
                break;
            case R.id.exit:
                finish();
                break;
        }
        return true;
    }

    @Override
    public void onBackPressed() {
        if (mDrawer.isDrawerOpen(GravityCompat.START)) {
            mDrawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login_or_up:
                startActivity(new Intent(MainActivity.this, LoginActivity.class));
                finish();
                break;
            case R.id.main_float_btn:
                if (UserUtil.isLogin()){
                    showDialogAddCard();
                }

                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CODE_PICK_CITY:
                if (resultCode == RESULT_OK) {
                    if (data != null) {
                        String city = data.getStringExtra(CityPickerActivity.KEY_PICKED_CITY);
                        menuLocation.setTitle(city);
                        currentCity = city;
                        ForumFragment forumFragment = (ForumFragment) mVpAdapter.getItem(1);
                        forumFragment.setCurrentCity(currentCity);
                        ChatRingFragment chatRingFragment = (ChatRingFragment) mVpAdapter.getItem(2);
                        chatRingFragment.setCurrentCity(currentCity);
                        ClassifyInfoFragment classifyInfoFragment = (ClassifyInfoFragment) mVpAdapter.getItem(0);
                        classifyInfoFragment.setCurrentCity(currentCity);
                        //TODO 更新界面
                    }
                }
                break;
        }
    }


    public static void startMainActivtyFromLoginActivity(Activity activity) {
        Intent intent = new Intent(activity, LogupActivity.class);
        activity.startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
        }
    }

    @Override
    public void getPath(Uri currentPath) {
        //更新头像
        Log.d("setImageURI", currentPath+"");
        naviUserHp.setImageURI(currentPath);
        UserUtil.saveAndUpdateUserHeadImg(Uri.parse(currentPath+""));
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION:{
                if(grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED){
                    //同意权限许可
                    //做你需要做的与联系人相关的任务
                    initLocationInfo();
                } else {
                    //禁用依赖于此权限的功能
                }
                break;
            }
        }
    }


}
